package com.yzg.explanation;

import java.util.HashMap;
import java.util.Stack;

public class Calculator {

	private Expression expression;

	public Calculator(String expStr) { // expStr = a+b
		//获取栈对象
		Stack<Expression> stack = new Stack<>();
		char[] charArray = expStr.toCharArray();// [a, +, b]

		Expression left = null;
		Expression right = null;
		// a + c   对应的就是  [a,+,c]
		for (int i = 0; i < charArray.length; i++) {
			switch (charArray[i]) {
			case '+': //
				left = stack.pop();// 栈中弹出
				right = new VarExpression(String.valueOf(charArray[++i]));//
				stack.push(new AddExpression(left, right));
				break;
			case '-': // 
				left = stack.pop();
				right = new VarExpression(String.valueOf(charArray[++i]));
				stack.push(new SubExpression(left, right));
				break;
			default: 
				stack.push(new VarExpression(String.valueOf(charArray[i])));
				break;
			}
		}
		//经过 switch 推理出 使用那个解释器去操作
		this.expression = stack.pop();
	}

	public int run(HashMap<String, Integer> var) {
		return this.expression.interpreter(var);
	}
}